const express = require("express");
const JWT = require("../utils/jwtUtil");

/* 创建路由器对象 */
const router = express.Router();

/* 定义路由 */
router.get("/", (req, res) => {
  res.end("Hello from indexRouter");
});

// GET /get?name=heige&pwd=123456
// searchParams queryString
router.get("/get", (req, res) => {
  res.end(
    JSON.stringify({
      ...req.query,
    })
  );
});

// POST http://localhost:8002/post
// router.post("/post", urlencodedParser, function (req, res) {
router.post("/post", function (req, res) {
  // res.send(
  //     JSON.stringify({
  //         msg:"msg from /post",
  //         ...req.body
  //     })
  // );

  res.json({
    msg: "msg from /post",
    ...req.body,
  });
});

router.get("/testtoken", (req, res) => {
  /* 提取token */
  let token = req.headers["authorization"];
  const regToken = /Bearer (.+)/;
  token = regToken.exec(token)[1];
  console.log("token=", token);

  const payload = JWT.verify(token);

  if (payload) {
    /* 有token且校验通过就返回内容 */
    res.json({ msg: "为已登录用户提供的香喷喷的内容", token, payload });
  } else {
    /* 否则返回请先登录 */
    res.json({ msg: "请先登录" });
  }
});

module.exports = router;
